<template>
  <div>
    <div v-for="(item, index) in banners" :key="index" class="banner-item">
      <el-image :src="item.image" style="width: 120px; height: 80px; object-fit: cover;" />
      <div class="banner-meta">
        <el-input v-model="item.url" placeholder="跳转链接（如 /pages/detail?id=123）" size="mini" />
        <el-button type="text" size="mini" @click="removeBanner(index)">删除</el-button>
      </div>
    </div>

    <el-button type="primary" size="small" icon="el-icon-plus" @click="addBanner">添加轮播图</el-button>
    <el-button type="success" size="small" @click="submit">保存顺序与链接</el-button>
  </div>
</template>

<script>
import Sortable from 'sortablejs';

export default {
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      banners: []
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.banners = JSON.parse(JSON.stringify(val || []));
      }
    }
  },
  mounted() {
    this.initSortable();
  },
  methods: {
    initSortable() {
      const el = this.$el;
      Sortable.create(el, {
        handle: '.banner-item',
        onEnd: evt => {
          const moved = this.banners.splice(evt.oldIndex, 1)[0];
          this.banners.splice(evt.newIndex, 0, moved);
        }
      });
    },
    addBanner() {
      this.banners.push({
        image: '',
        url: ''
      });
    },
    removeBanner(index) {
      this.banners.splice(index, 1);
    },
    submit() {
      this.$emit('input', this.banners);
      this.$emit('save', this.banners);
    }
  }
};
</script>

<style scoped>
.banner-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px dashed #ccc;
  cursor: move;
}
.banner-meta {
  flex: 1;
}
</style>
